package com.note.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.RequestContextUtil;
import com.note.domain.dto.PublishNoteDTO;
import com.note.domain.dto.UpdateNoteDTO;
import com.note.domain.entity.Note;
import com.note.domain.vo.NoteStatsVO;
import com.note.mapper.NoteMapper;
import com.note.service.INoteService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 笔记表 服务实现类
 * </p>
 *
 * @author 坤哥
 * @since 2025-10-11
 */
@Service
public class NoteServiceImpl extends ServiceImpl<NoteMapper, Note> implements INoteService {

    @Override
    public void publishNote(PublishNoteDTO publishNoteDTO) {
        // 获取当前用户ID
        Long userId = RequestContextUtil.getCurrentUserId();
        
        // 创建笔记对象
        Note note = new Note();
        note.setUserId(userId);
        note.setTitle(publishNoteDTO.getTitle());
        note.setContent(publishNoteDTO.getContent());
        note.setStatus("0");
        note.setCreateTime(LocalDateTime.now());
        note.setUpdateTime(LocalDateTime.now());
        
        // 保存到数据库
        save(note);
    }

    @Override
    public IPage<Note> getNoteList(String title, Integer pageNum, Integer pageSize) {
        // 获取当前用户ID
        Long userId = RequestContextUtil.getCurrentUserId();
        
        // 构建分页对象
        Page<Note> page = new Page<>(pageNum, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<Note> wrapper = new LambdaQueryWrapper<>();
        
        // 只查询当前用户的笔记
        wrapper.eq(Note::getUserId, userId);
        
        // 只查询未删除的笔记
        wrapper.eq(Note::getStatus, "0");
        
        // 标题模糊查询
        wrapper.like(StrUtil.isNotBlank(title), Note::getTitle, title);
        
        // 按创建时间倒序排列
        wrapper.orderByDesc(Note::getCreateTime);
        
        // 执行分页查询
        return page(page, wrapper);
    }

    @Override
    public IPage<Note> getAllNoteList(String title, Integer pageNum, Integer pageSize) {
        // 构建分页对象
        Page<Note> page = new Page<>(pageNum, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<Note> wrapper = new LambdaQueryWrapper<>();
        
        // 只查询未删除的笔记
        wrapper.eq(Note::getStatus, "0");
        
        // 标题模糊查询
        wrapper.like(StrUtil.isNotBlank(title), Note::getTitle, title);
        
        // 按创建时间倒序排列
        wrapper.orderByDesc(Note::getCreateTime);
        
        // 执行分页查询
        return page(page, wrapper);
    }

    @Override
    public void deleteNote(Long id) {
        // 获取当前用户ID
        Long userId = RequestContextUtil.getCurrentUserId();
        
        // 验证笔记是否存在且属于当前用户
        Note note = getById(id);
        if (note == null) {
            throw new RuntimeException("笔记不存在");
        }
        if (!note.getUserId().equals(userId)) {
            throw new RuntimeException("无权删除该笔记");
        }
        
        // 软删除（更新状态为1）
        LambdaUpdateWrapper<Note> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Note::getId, id);
        wrapper.eq(Note::getUserId, userId);
        wrapper.set(Note::getStatus, "1");
        wrapper.set(Note::getUpdateTime, LocalDateTime.now());
        
        update(wrapper);
    }

    @Override
    public void updateNote(UpdateNoteDTO updateNoteDTO) {
        // 获取当前用户ID
        Long userId = RequestContextUtil.getCurrentUserId();
        
        // 验证笔记是否存在且属于当前用户
        Note note = getById(updateNoteDTO.getId());
        if (note == null) {
            throw new RuntimeException("笔记不存在");
        }
        if (!note.getUserId().equals(userId)) {
            throw new RuntimeException("无权修改该笔记");
        }
        
        // 更新笔记
        LambdaUpdateWrapper<Note> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(Note::getId, updateNoteDTO.getId());
        wrapper.eq(Note::getUserId, userId);
        wrapper.set(Note::getTitle, updateNoteDTO.getTitle());
        wrapper.set(Note::getContent, updateNoteDTO.getContent());
        wrapper.set(Note::getUpdateTime, LocalDateTime.now());
        
        update(wrapper);
    }

    @Override
    public NoteStatsVO getNoteStats() {
        // 获取当前用户ID
        Long userId = RequestContextUtil.getCurrentUserId();
        
        // 计算7天前的时间
        LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
        
        // 1. 统计我的笔记总数（未删除的）
        LambdaQueryWrapper<Note> myNoteWrapper = new LambdaQueryWrapper<>();
        myNoteWrapper.eq(Note::getUserId, userId);
        myNoteWrapper.eq(Note::getStatus, "0");
        Long myNoteCount = count(myNoteWrapper);
        
        // 2. 统计最近7天新增的笔记数量
        LambdaQueryWrapper<Note> recentCreateWrapper = new LambdaQueryWrapper<>();
        recentCreateWrapper.eq(Note::getUserId, userId);
        recentCreateWrapper.eq(Note::getStatus, "0");
        recentCreateWrapper.ge(Note::getCreateTime, sevenDaysAgo);
        Long favoriteCount = count(recentCreateWrapper);
        
        // 3. 统计最近7天编辑的笔记数量（update_time在最近7天内且不等于create_time）
        LambdaQueryWrapper<Note> recentEditWrapper = new LambdaQueryWrapper<>();
        recentEditWrapper.eq(Note::getUserId, userId);
        recentEditWrapper.eq(Note::getStatus, "0");
        recentEditWrapper.ge(Note::getUpdateTime, sevenDaysAgo);
        // 排除刚创建的笔记（create_time != update_time）
        recentEditWrapper.apply("update_time > create_time");
        Long recentEditCount = count(recentEditWrapper);
        
        // 构建返回对象
        return new NoteStatsVO(
            myNoteCount.intValue(),
            favoriteCount.intValue(),
            recentEditCount.intValue()
        );
    }
}

